import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'
import { compression } from 'vite-plugin-compression2'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import Pages from 'vite-plugin-pages'
import { camelCase, upperFirst } from 'lodash-es'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import UnoCSS from 'unocss/vite'
import postcsspxtoviewport8plugin from 'postcss-px-to-viewport-8-plugin'
import fs from 'fs'

// 使用optimizeDeps.include预加载资源
const optimizeDepsElementPlusIncludes = ['element-plus', 'lodash', 'lodash-es', 'dayjs', 'sortablejs', 'js-file-download', '@iconify/vue', '@wangeditor/editor-for-vue']
fs.readdirSync('node_modules/element-plus/es/components').forEach((dirname) => {
  fs.access(
      `node_modules/element-plus/es/components/${dirname}/style/css.mjs`,
      (err) => {
        if (err) return
        optimizeDepsElementPlusIncludes.push(
            `element-plus/es/components/${dirname}/style/css`
        )
      }
  )
})
// https://vitejs.dev/config/
export default defineConfig({
  optimizeDeps: {
    include: optimizeDepsElementPlusIncludes
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        // api: 'modern-compiler',
        // 相当于给给每个组件scss中插入字符串
        additionalData: '@use "@/styles/variables.scss" as *;'
      }
    },
    postcss: {
      plugins: [
        postcsspxtoviewport8plugin({
          unitToConvert: 'rpx',
          viewportWidth: '750',
          exclude: [/node_modules/],
          include: [/src/]
        })
      ]
    }
  },
  plugins: [
    vue(),
    eslintPlugin(),
    compression(),
    Pages({
      dirs: [
        { dir: 'src/pages', baseRoute: '' },
        { dir: 'src/views', baseRoute: '' }
      ],
      extensions: ['vue'],
      exclude: ['**/components/**/*.vue'],
      importMode (filepath) {
        return filepath.includes('views') ? 'async' : 'sync'
      },
      extendRoute (route) {
        // 将组件名称处理为大驼峰
        route.name = upperFirst(camelCase(route.name))

        // views目录下的文件添加权限控制
        const str = 'views'
        if (route.path !== '/' && route.component.includes(str)) {
          route.meta = Object.assign(route.meta || {}, {
            requiresAuth: true
          })
        }

        return route
      }
    }),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      dts: './src/types/auto-imports.d.ts',
      eslintrc: {
        enabled: false, // Default `false`
        filepath: './src/types/.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
      imports: [
        // 插件预设支持导入的api
        'vue',
        'vue-router',
        'pinia'
      ]
    }),
    Components({
      globs: ['src/components/*/*.vue'],
      resolvers: [ElementPlusResolver()],
      dts: './src/types/components.d.ts'
    }),
    UnoCSS({
      configFile: '../uno.config.ts'
    })
  ],
  server: {
    host: '0.0.0.0',
    port: 9527
  },
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
})
